package com.zhy.generator.codegen.mybatis.javavo;

import com.zhy.generator.codegen.api.CommentGenerator;
import com.zhy.generator.codegen.api.IntrospectedColumn;
import com.zhy.generator.codegen.api.Plugin;
import com.zhy.generator.codegen.dom.java.*;
import com.zhy.generator.codegen.mybatis.AbstractJavaGenerator;
import com.zhy.generator.codegen.mybatis.RootClassInfo;
import com.zhy.generator.config.Configuration;
import com.zhy.generator.config.ConfigurationConstant;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static cn.hutool.core.util.StrUtil.isNotBlank;
import static com.zhy.generator.codegen.util.JavaBeansUtil.*;
import static com.zhy.generator.codegen.util.Messages.getString;

/**
 * @author 源
 */
public class JavaVoGenerator extends AbstractJavaGenerator {

    public JavaVoGenerator() {
        super();
    }

    @Override
    public List<CompilationUnit> getCompilationUnits() {
//        FullyQualifiedTable table = introspectedTable.getFullyQualifiedTable();
//
        progressCallback.startTask(getString("Progress.9", introspectedTable.getFullyQualifiedTable())); //$NON-NLS-1$

        Plugin plugins = context.getPlugins();

        CommentGenerator commentGenerator = context.getCommentGenerator();

        FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getVoType());

        TopLevelClass topLevelClass = new TopLevelClass(type);
        topLevelClass.setVisibility(JavaVisibility.PUBLIC);

        commentGenerator.addJavaFileComment(topLevelClass);

        FullyQualifiedJavaType superClass = getSuperClass();

        if (superClass != null) {
            topLevelClass.setSuperClass(superClass);
            topLevelClass.addImportedType(superClass);
        }

        commentGenerator.addModelClassComment(topLevelClass, introspectedTable);

        //serialVersionUID
        addSerialVersionUIDField(topLevelClass);

        List<IntrospectedColumn> introspectedColumns = getColumnsInThisClass();

//        //是否添加构造函数
//        if (introspectedTable.isConstructorBased()) {
//
//            //添加构造函数的参数-不包括BLOB字段
//            addParameterizedConstructor(topLevelClass, introspectedTable.getNonBLOBColumns());
//
//            //添加构造函数的参数-包括BLOB字段
//            if (includeBLOBColumns()) {
//                addParameterizedConstructor(topLevelClass, introspectedTable.getAllColumns());
//            }
//
//            //添加默认构造函数
//            if (!introspectedTable.isImmutable()) {
//                addDefaultConstructor(topLevelClass);
//            }
//        }

        String rootClass = getSuperClass().getFullyQualifiedName();
        for (IntrospectedColumn introspectedColumn : introspectedColumns) {
            if (RootClassInfo.getInstance(rootClass, warnings).containsProperty(introspectedColumn)) {
                continue;
            }

            Field field = getJavaBeansField(introspectedColumn, context, introspectedTable);
            if (plugins.voFieldGenerated(field, topLevelClass,introspectedColumn, introspectedTable, Plugin.ModelClassType.BASE_RECORD)) {
                topLevelClass.addField(field);
                topLevelClass.addImportedType(field.getType());
            }

            String remarks = introspectedColumn.getRemarks();
            if(!StringUtils.isEmpty(remarks) && remarks.startsWith("constant")){
                Field lableField = new Field();
                lableField.setVisibility(JavaVisibility.PRIVATE);
                lableField.setType(FullyQualifiedJavaType.getStringInstance());
                lableField.setName(introspectedColumn.getJavaProperty()+"Lable");
                context.getCommentGenerator().addFieldComment(lableField,introspectedTable, introspectedColumn);
                if (plugins.voFieldGenerated(lableField, topLevelClass,introspectedColumn, introspectedTable, Plugin.ModelClassType.BASE_RECORD)) {
                    topLevelClass.addField(lableField);
                    topLevelClass.addImportedType(lableField.getType());
                }
            }

            Method method = getJavaBeansGetter(introspectedColumn, context, introspectedTable);
            if (plugins.modelGetterMethodGenerated(method, topLevelClass,introspectedColumn, introspectedTable,Plugin.ModelClassType.BASE_RECORD)) {
                topLevelClass.addMethod(method);
            }

//            if (!introspectedTable.isImmutable()) {
//                method = getJavaBeansSetter(introspectedColumn, context, introspectedTable);
//                if (plugins.modelSetterMethodGenerated(method, topLevelClass,introspectedColumn, introspectedTable,Plugin.ModelClassType.BASE_RECORD)) {
//                    topLevelClass.addMethod(method);
//                }
//            }
        }

        List<CompilationUnit> answer = new ArrayList<CompilationUnit>();
        if (context.getPlugins().voClassGenerated(topLevelClass, introspectedTable)) {
            answer.add(topLevelClass);
        }
        return answer;
    }

    private FullyQualifiedJavaType getSuperClass() {

        Configuration javaVoGeneratorConfiguration = context.getConfiguration(ConfigurationConstant.CONFIGURATION_VO);
        if(javaVoGeneratorConfiguration == null){
            return null;
        }
        String rootClass = javaVoGeneratorConfiguration.getRootClass();
        if (isNotBlank(rootClass)) {
            FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(rootClass);
            return fqjt;
        }

        return null;
    }

    private List<IntrospectedColumn> getColumnsInThisClass() {
        List<IntrospectedColumn> introspectedColumns;
        if (includePrimaryKeyColumns()) {
            if (includeBLOBColumns()) {
                introspectedColumns = introspectedTable.getAllColumns();
            } else {
                introspectedColumns = introspectedTable.getNonBLOBColumns();
            }
        } else {
            if (includeBLOBColumns()) {
                introspectedColumns = introspectedTable.getNonPrimaryKeyColumns();
            } else {
                introspectedColumns = introspectedTable.getBaseColumns();
            }
        }

        return introspectedColumns;
    }

    private boolean includePrimaryKeyColumns() {
        return !introspectedTable.getRules().generatePrimaryKeyClass() && introspectedTable.hasPrimaryKeyColumns();
    }

    private boolean includeBLOBColumns() {
        return !introspectedTable.getRules().generateRecordWithBLOBsClass() && introspectedTable.hasBLOBColumns();
    }

    private void addParameterizedConstructor(TopLevelClass topLevelClass, List<IntrospectedColumn> constructorColumns) {
        Method method = new Method();
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setConstructor(true);
        method.setName(topLevelClass.getType().getShortName());
        context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);

        for (IntrospectedColumn introspectedColumn : constructorColumns) {
            method.addParameter(new Parameter(introspectedColumn.getFullyQualifiedJavaType(), introspectedColumn.getJavaProperty()));
            topLevelClass.addImportedType(introspectedColumn.getFullyQualifiedJavaType());
        }

        StringBuilder sb = new StringBuilder();
        List<String> superColumns = new LinkedList<String>();
        if (introspectedTable.getRules().generatePrimaryKeyClass()) {
            boolean comma = false;
            sb.append("super("); //$NON-NLS-1$
            for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
                if (comma) {
                    sb.append(", "); //$NON-NLS-1$
                } else {
                    comma = true;
                }
                sb.append(introspectedColumn.getJavaProperty());
                superColumns.add(introspectedColumn.getActualColumnName());
            }
            sb.append(");"); //$NON-NLS-1$
            method.addBodyLine(sb.toString());
        }

        for (IntrospectedColumn introspectedColumn : constructorColumns) {
            if (!superColumns.contains(introspectedColumn.getActualColumnName())) {
                sb.setLength(0);
                sb.append("this."); //$NON-NLS-1$
                sb.append(introspectedColumn.getJavaProperty());
                sb.append(" = "); //$NON-NLS-1$
                sb.append(introspectedColumn.getJavaProperty());
                sb.append(';');
                method.addBodyLine(sb.toString());
            }
        }

        topLevelClass.addMethod(method);
    }
}
